package edu.ncsu.csc.ip.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Class <code></code>
 * 
 * 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class ClientIndex {
	private static ClientIndex instance = null;

	public final static Integer TTL_UPDATE_INTERVAL = 60;

	private Map<Integer, ClientBean> clientIndexMap = new ConcurrentHashMap<Integer, ClientBean>();

	protected ClientIndex() {
		// Exists only to defeat instantiation.
	}

	public static ClientIndex getInstance() {
		if (instance == null) {
			instance = new ClientIndex();
		}
		return instance;
	}

	public Integer addClient(ClientBean clientBean) {

		//Do not add duplicate clients to the index
		//See ClientBean.equals
		if (clientIndexMap.containsValue(clientBean)) {
			for (ClientBean cb : clientIndexMap.values())
				if (clientBean.equals(cb))
					clientBean.setCookie(cb.getCookie());

		} else {
			clientBean.setCookie(getNewCookie());
		}

		clientIndexMap.put(clientBean.getCookie(), clientBean);
		return clientBean.getCookie();
	}

	public ClientBean getClient(Integer cookie) {
		return clientIndexMap.get(cookie);
	}

	public Map<Integer, ClientBean> getclientIndexMap() {
		return clientIndexMap;
	}

	private Integer getNewCookie() {
		int cookie = 0;
		for (Integer key : clientIndexMap.keySet()) {
			if (key > cookie)
				cookie = key;
		}
		return ++cookie;
	}

	public List<ClientBean> getActiveClients() {
		List<ClientBean> activeClients = new ArrayList<ClientBean>();
		for (ClientBean clientBean : clientIndexMap.values())
			if (clientBean.getActiveFlag() == true)
				activeClients.add(clientBean);
		return activeClients;
	}

	public List<ClientBean> getActiveClients(Integer cookie) {
		List<ClientBean> activeClients = new ArrayList<ClientBean>();
		for (ClientBean clientBean : clientIndexMap.values())
			if (clientBean.getActiveFlag() == true
					&& clientBean.getCookie() != cookie)
				activeClients.add(clientBean);
		return activeClients;
	}
}
